import { onMounted, ref } from 'vue'
import screenfull from 'screenfull'

/*
  screenfull.isFullscreen：检测是否全屏
  screenfull.isEnabled：检测是否支持全屏
  screenfull.request()：进入全屏
  screenfull.exit()：退出全屏，注意是退回到进入全屏的状态
  screenfull.toggle()：切换全屏，较常用
*/

const useScreenFull = () => {
  const isFullScreenTag = ref(false)

  const handleFullScreen = () => {
    if (screenfull.isEnabled) {
      // 检测当前是否全屏，如果是全屏就退出，否则就全屏
      if (isFullScreenTag.value) {
        screenfull.toggle()
        isFullScreenTag.value = false
        // screenfull.exit()
      } else {
        // 进入全屏
        screenfull.toggle()
        isFullScreenTag.value = true
        // screenfull.request()
      }
    } else {
      alert('提示：不支持切换全屏。')
    }
  }

  /* 
    综合视图全屏和退出全屏操作
    注意，我们不仅可以点击按钮进入全屏，我们点击F11也是可以进入全屏
  */
  const onDataViewFullscreenSwitch = () => {
    /* 当前已经处于全屏状态下，我们进入全屏，全屏窗口不应该切换 */
    if (isFullScreenTag.value && screenfull.isFullscreen) {
      return
    }

    /* 当前已经处于不全屏状态下，我们进入退出全屏，全屏窗口不应该切换 */
    if (!isFullScreenTag.value && !screenfull.isFullscreen) {
      return
    }

    if (screenfull.isEnabled) {
      screenfull.toggle()
    } else {
      alert('提示：不支持切换全屏。')
    }
  }

  onMounted(() => {
    screenfull.onchange(() => {
      // 当数据视图处于全屏状态时，点击 ESC 按键应该退出全屏状态
      if (!screenfull.isFullscreen && isFullScreenTag.value) {
        isFullScreenTag.value = false
      }
    })
  })

  return { isFullScreenTag, handleFullScreen, onDataViewFullscreenSwitch }
}

export default useScreenFull
